<template>
  <!-- 平台上所有服务  包含已开通和尾开通的服务 -->
  <div class="server_box customTab" v-loading="loading">
    <el-tabs type="border-card" v-model="tabActive" @tab-click="tabChange">
      <el-tab-pane label="系统服务" name="1">
        <div class="service-box ">
          <!-- <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="auto">
              <div class="search-box">
                <el-form-item label="状态" prop="state">
                  <el-select clearable filterable v-model="queryParams.state" placeholder="请选择状态" size="small" @change="getMyService">
                    <el-option v-for="(value,key) in commonMaps.addedServicesStateMap" :key="key" :label="value.label" :value="key" />
                  </el-select>
                </el-form-item>
              </div>
            </el-form> -->
          <div class="content flex" v-if="menuGroupList&&menuGroupList.length&&serviceList">
            <div class="service-item " :class="{'jjdq':dayNum(item.closeTime)<7&&dayNum(item.closeTime)>=0,'zc':item.state==1,'dq':item.state==2,'wkt':!item.businessId}" v-for="(item,i) in menuGroupList" :key="i">
              <div class="top">
                <div class="name flex">
                  <!-- <span @click="item.checked = !item.checked" v-show="item.type==2" class="check-box" :class="{checked:item.checked}"></span> -->
                  {{item.groupName}}
                </div>
                <div class="endtime" v-if="item.businessId"><span>到期时间：</span>{{item.closeTime}}</div>
                <div class="sign" v-text="dayNum(item.closeTime)<5&&dayNum(item.closeTime)>=0?'即将到期':(item.state==1?'正常':(item.businessId? '到期':'未开通'))">
                </div>
                <div class="auto" v-if="item.businessId!=5492">
                  <span>自动续费：</span>
                  <el-switch @change="editAuto(item)" :disabled="nowDate==item.closeTime" v-model="item.isAuto" :active-value="1" :inactive-value="2" active-color="#24A813" inactive-color="#999999">
                  </el-switch>
                </div>
                <div class="tip" v-if="item.businessId!=5492">
                  {{`自动续费开启后，系统将在服务有效期最后一天，续费1个月。`}}
                </div>
                <div v-else>
                  {{`该功能开通后系统每月自动检测业务量，不符合使用条件的会自动停用该功能`}}
                </div>
              </div>
              <div class="btns">
                <el-button v-if="item.businessId" plain size="small" type="danger" @click="guanbi(item)" v-loading="loading">关闭服务</el-button>
                <!-- <el-button style="background-color:#fff;border:1px solid #f2f2f2" size="small" @click="lianxi(item.businessId)" v-if="item.type==2">联系技术</el-button> -->
                <el-button v-if="!item.businessId" size="small" type="primary" @click="kaitong(item)" v-loading="loading">开通</el-button>

                <el-button v-if="(item.buyWay==2&&item.businessId)||(item.buyWay!=2&&item.businessId==5492&&item.state!=1)" size="small" type="primary" @click="submitForm(item)" v-loading="loading">续费</el-button>
                <span v-else-if="item.buyWay!=2&&item.businessId" style="color:#24A813;margin-left: 10px;">已开通长期</span>
              </div>
            </div>
          </div>
          <div v-else style="text-align:center;line-height:300px">
            暂未开通任何服务
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="接口渠道" name="2">
        <div class="allQudao">
          <el-descriptions class="margin-top" title="" :column="1" border>
            <el-descriptions-item label="所有接口渠道" :labelStyle="{width:'110px'}">
              <div class="list-box flex" v-if="plantformList&&serviceList">
                <div v-for="(item,index) in plantformList" :key="index">
                  <div @click="openInterface(item)" class="plantform-item" v-if="item.isShow==1&&!item.isHide">
                    {{item.name}}
                    <span v-if="item.businessId">(已开通 <span v-if="item.cont&&item.cont>1">{{item.cont}}</span> )</span>
                  </div>

                </div>
              </div>
            </el-descriptions-item>
            <el-descriptions-item v-if="userInfo.userId==1" label="客服上架渠道" :labelStyle="{width:'110px'}">
              <div class="list-box flex" v-if="plantformList&&serviceList">
                <div v-for="(item,index) in plantformList" :key="index">
                  <div @click="openInterface(item)" class="plantform-item" v-if="item.isHide">
                    {{item.name}}
                    <span v-if="item.businessId">(已开通 <span v-if="item.cont&&item.cont>1">{{item.cont}}</span> )</span>
                  </div>
                </div>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="service-box ">
          <el-descriptions class="margin-top" title="" :column="1" border>
            <el-descriptions-item label="已开通接口" :labelStyle="{width:'120px'}">
              <div class="content flex" v-if="myServiceList&&myServiceList.length">
                <div class="service-item " :class="{'jjdq':dayNum(item.closeTime)<7&&dayNum(item.closeTime)>=0,'zc':item.state==1,'dq':item.state==2}" v-for="(item,i) in myServiceList.filter(r=>{return r.channelType==1})" :key="i">
                  <div class="top">
                    <div class="name flex">
                      <!-- <span @click="item.checked = !item.checked" v-show="item.type==2" class="check-box" :class="{checked:item.checked}"></span> -->
                      {{item.businessName}}
                    </div>
                    <div class="endtime"><span>到期时间：</span>{{item.closeTime}}</div>
                    <div class="sign" v-text="dayNum(item.closeTime)<5&&dayNum(item.closeTime)>=0?'即将到期':(item.state==1?'正常':(item.businessId? '到期':'未开通'))">
                    </div>
                    <div class="auto">
                      <span>自动续费：</span>
                      <el-switch @change="editAuto(item)" :disabled="nowDate==item.closeTime" v-model="item.isAuto" :active-value="1" :inactive-value="2" active-color="#24A813" inactive-color="#999999">
                      </el-switch>
                    </div>
                    <div class="tip">
                      {{`自动续费开启后，系统将在服务有效期最后一天，续费1个月。`}}
                    </div>
                  </div>
                  <div class="btns">
                    <!-- <el-button style="background-color:#fff;border:1px solid #f2f2f2" size="small" @click="lianxi(item.businessId)" v-if="item.type==2">联系技术</el-button> -->
                    <!-- <el-button v-if="!item.businessId" size="small" type="primary" @click="kaitong(item)" v-loading="loading">开通</el-button> -->
                    <el-button v-if="item.buyWay==2&&item.businessId" size="small" type="primary" @click="xufeiApi(item)" v-loading="loading">续费</el-button>
                    <span v-if="(item.buyWay==3||item.buyWay==1)&&item.businessId" style="color:#24A813">已开通长期</span>
                  </div>
                </div>
              </div>
              <div v-else style="text-align:center;line-height:300px">
                暂未开通任何服务
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="已开通客服上架" :labelStyle="{width:'120px'}" v-if="myServiceList&&myServiceList.length&&myServiceList.filter(r=>{return r.channelType==2}).length>0">
              <div class="content flex">
                <div class="service-item " :class="{'jjdq':dayNum(item.closeTime)<7&&dayNum(item.closeTime)>=0,'zc':item.state==1,'dq':item.state==2}" v-for="(item,i) in myServiceList.filter(r=>{return r.channelType==2})" :key="i">
                  <div class="top">
                    <div class="name flex">
                      <!-- <span @click="item.checked = !item.checked" v-show="item.type==2" class="check-box" :class="{checked:item.checked}"></span> -->
                      {{item.businessName}}
                    </div>
                    <div class="endtime"><span>到期时间：</span>{{item.closeTime}}</div>
                    <div class="sign" v-text="dayNum(item.closeTime)<5&&dayNum(item.closeTime)>=0?'即将到期':(item.state==1?'正常':(item.businessId? '到期':'未开通'))">
                    </div>
                    <!-- <div class="auto" >
                        <span>自动续费：</span>
                        <el-switch
                          @change="editAuto($event,item)"
                          :disabled="nowDate==item.closeTime"
                          v-model="item.isAuto"
                          :active-value="1"
                          :inactive-value="2"
                          active-color="#24A813"
                          inactive-color="#999999">
                        </el-switch>
                      </div>
                      <div class="tip" >
                        {{`自动续费开启后，系统将在服务有效期最后一天，续费1个月。`}}
                      </div> -->
                  </div>
                  <div class="btns">
                    <!-- <el-button style="background-color:#fff;border:1px solid #f2f2f2" size="small" @click="lianxi(item.businessId)" v-if="item.type==2">联系技术</el-button> -->
                    <!-- <el-button v-if="!item.businessId" size="small" type="primary" @click="kaitong(item)" v-loading="loading">开通</el-button> -->
                    <el-button v-if="item.buyWay==2&&item.businessId" size="small" type="primary" @click="xufeiApi(item)" v-loading="loading">续费</el-button>
                    <span v-if="(item.buyWay==3||item.buyWay==1)&&item.businessId" style="color:#24A813">已开通长期</span>
                    <!-- <span style="color:#24A813">请联系商务续费</span> -->
                  </div>
                </div>
              </div>
            </el-descriptions-item>
          </el-descriptions>

        </div>
      </el-tab-pane>
      <el-tab-pane label="商城主题" name="3">
        <div class="allQudao">
          <themeOpenVue ref="themeOpenVue" :tenantId="tenantIdCur" @kaitong="kaitong" @xufei="submitForm"></themeOpenVue>
        </div>
      </el-tab-pane>
      <el-tab-pane label="账号坑位管理" name="4">
        <div class="allQudao">
          <ChuZuShang ref="ChuZuShang"></ChuZuShang>
        </div>
      </el-tab-pane>
    </el-tabs>

    <moduleOpenDialog :tenantId="tenantIdCur" :campNumber="campNumberCur" ref="moduleOpenDialog" @success="init"></moduleOpenDialog>
    <apiOpenDialog :tenantId="tenantIdCur" :campNumber="campNumberCur" ref="apiOpenDialog" @success="init"></apiOpenDialog>
  </div>
</template>

<script>
import { menuGroupList } from "@/api/system/menuGroup.js";
import interfaceChannelApi from "@/api/shanghuduan/interfaceChannel.js";
import tabBar from "@/components/tenant/tabBar.vue";
import valueAddedServices from "@/api/shanghuduan/valueAddedServices";
import { formatDate } from "@/utils/index";
import themeOpenVue from "./themeOpenVue.vue";
import ChuZuShang from "./chuZuShang.vue";

// 开通弹窗
import moduleOpenDialog from "./moduleOpenDialog.vue";
import apiOpenDialog from "./apiOpenDialog.vue";

import { mapGetters } from "vuex";
export default {
  name: "",
  props: ["tenantId", "campNumber", "pageType"],
  components: {
    tabBar,
    moduleOpenDialog,
    apiOpenDialog,
    themeOpenVue,
    ChuZuShang,
  },
  data() {
    return {
      tabActive: "1",
      loading: false,
      tabs: [
        {
          name: "系统服务",
          value: "1",
        },
        {
          name: "接口渠道",
          value: "2",
        },
      ],
      allCheck: false,
      serviceList: null,
      // 查询参数
      queryParams: {
        closeTimeStart: "",
        closeTimeEnd: "",
        dataType: "all",
        type: "1",
      },
      nowDate: "",

      menuGroupList: [],
      tenantIdCur: "", //当前租户id
      campNumberCur: "", //当前租户id
      plantformList: null, //所有的接口渠道平台
      myServiceList: null, //已开通的接口服务
    };
  },
  watch: {
    tenantId: {
      handler(newVal) {
        this.tenantIdCur = newVal;
        this.getmenuGroupList();
      },
      immediate: true,
    },
    campNumber: {
      handler(newVal) {
        this.campNumberCur = newVal;
      },
      immediate: true,
    },
  },
  created() {
    let date = new Date();
    this.nowDate = formatDate(date).slice(0, 10);
  },
  computed: {
    ...mapGetters(["userInfo"]),
    dayNum() {
      return (val) => {
        let date = Date.parse(new Date(val)) / 1000;
        var today = Date.parse(new Date()) / 1000; //当前时间戳
        var nTime = date - today;
        var day = Math.floor(nTime / 86400) + 1;
        return day;
      };
    },
  },
  methods: {
    init() {
      if (this.tabActive == 1) {
        this.getmenuGroupList();
      } else if (this.tabActive == 2) {
        this.getQudaoList();
      } else if (this.tabActive == 3) {
        this.$refs.themeOpenVue.getthemeList();
      }
    },
    tabChange(val) {
      this.tabActive = val.name;
      this.queryParams.type = val.name;
      this.serviceList = null;
      this.init();
    },
    // 获取所有的菜单分组（功能模块）
    getmenuGroupList() {
      this.loading = true;
      menuGroupList({ status: this.pageType == "admin" ? "" : "0" }).then(
        (response) => {
          this.menuGroupList = response.rows;
          // this.total = response.total;
          this.getMyService(this.tenantIdCur);
          this.loading = false;
        }
      );
    },
    // 获取所有的接口渠道
    getQudaoList() {
      this.loading = true;
      interfaceChannelApi.getAllList({ isPage: 2 }).then((res) => {
        this.plantformList = res.rows;
        this.getMyService(this.tenantIdCur);
        this.loading = false;
      });
    },
    // 开通功能模块服务
    kaitong(item) {
      let type = 1;
      if (item.serveType) type = item.serveType;
      this.$refs.moduleOpenDialog.open(item, 1, type);
    },
    // 关闭服务
    guanbi(item) {
      this.$confirm("关闭后商户无法使用相关功能，确定关闭吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          valueAddedServices.closeAndDelService({
            tenantId:item.tenantId,
            groupId:item.groupId
          }).then(res=>{
            if(res.code==200){
              this.$message.success(res.msg)
              this.getMyService(this.tenantIdCur);
            }else{
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          
        });
    },
    // 开通接口渠道
    openInterface(item) {
      // if(item.businessId){
      //   return
      // }
      let type = 1;
      if (item.serveType) type = item.serveType;
      this.$refs.apiOpenDialog.open(item, 1, type);
    },
    // 获取租户开通的增值服务
    getMyService(tenantId) {
      // if()
      this.queryParams.tenantId = tenantId;
      valueAddedServices
        .myValueAddedServiceList(this.queryParams)
        .then((res) => {
          if (res.rows && res.rows.length) {
            this.serviceList = res.rows;
          } else {
            this.serviceList = [];
          }
          this.mergeServices();
        });
    },
    // 合并获取到的已开通服务和全部服务列表
    mergeServices() {
      if (this.serviceList && this.serviceList.length) {
        if (this.tabActive == 1) {
          this.menuGroupList.forEach((r1, i1) => {
            this.serviceList.forEach((r2) => {
              if (r1.groupId == r2.businessId) {
                this.menuGroupList[i1] = { ...r1, ...r2 };
              }
            });
          });
        } else if (this.tabActive == 2) {
          this.myServiceList = this.serviceList;
          this.plantformList.forEach((r1, i1) => {
            let cont = 0;
            if (r1.channelType == 2) {
              r1.isHide = true;
            }
            this.serviceList.forEach((r2, i2) => {
              if (r1.id == r2.businessId) {
                cont++;
                this.plantformList[i1] = { ...r1, ...r2 };
                this.myServiceList[i2] = { ...r1, ...r2 };
              }
            });
            if (cont) {
              this.plantformList[i1].cont = cont;
            }
          });
        }
      } else {
        if (this.tabActive == 2) {
          this.plantformList.forEach((r1, i1) => {
            if (r1.channelType == 2) {
              r1.isHide = true;
            }
          });
        }
      }
      this.$forceUpdate();
    },
    // 改变自动续费状态
    editAuto(item) {
      console.log("%c Line:384 🥝 item", "color:#ea7e5c", item);
      valueAddedServices.myValueAddedServiceChangeAuto(item).then((res) => {
        this.getMyService(item.tenantId);
      });
    },
    // 全选
    selectAll(e) {
      if (e) {
        this.serviceList.forEach((r) => {
          r.checked = true;
        });
      } else {
        this.serviceList.forEach((r) => {
          r.checked = false;
        });
      }
    },
    // 续费API
    xufeiApi(item) {
      console.log("%c Line:394 🥝 item", "color:#ea7e5c", item);
      // let flag=2
      // if(this.dayNum(item.closeTime)<=0){
      //   // 已到期
      //   flag =3
      // }
      this.$refs.apiOpenDialog.open(item, 2);
    },
    // 续费 主题
    submitForm(item) {
      console.log("%c Line:389 🍿 item", "color:#3f7cff", item);
      let type = 1;
      if (item.serveType) {
        type = item.serveType;
        item.groupId = item.businessId;
      }
      this.$refs.moduleOpenDialog.open(item, 2, type);
    },
    lianxi(id) {
      this.$refs.contactServer.open(id);
    },
  },
};
</script>
<style scoped lang="scss">
.server_box {
  .service-box {
    min-height: calc(100vh - 200px);
    background-color: #fff;
    .content {
      flex-wrap: wrap;
    }
    .service-item {
      border: 1px solid #24a813;
      width: 235px;
      // height: 130px;
      border-radius: 10px;
      margin: 0 0 10px 10px;
      position: relative;
      overflow: hidden;
      color: #fff;
      line-height: 22px;
      .top {
        padding: 15px;
        background-color: #8cc7a3;
        min-height: 160px;
        .name {
          align-items: center;
          margin-bottom: 10px;
          font-size: 18px;
          .check-box {
            width: 16px;
            height: 16px;
            background-image: url("../../assets/img/uncheck.png");
            background-size: 100% 100%;
            margin-right: 5px;
            cursor: pointer;
            &.checked {
              background-image: url("../../assets/img/checked2.png");
            }
          }
        }
      }
      .btns {
        text-align: center;
        padding: 10px 0;
        background-color: #fff;
        .el-button.el-button--primary {
          background-color: #24a813;
          border: #24a813;
        }
      }
      .tip {
        margin-top: 10px;
      }
      .sign {
        position: absolute;
        top: 0;
        right: 0;
        font-size: 12px;
        color: #24a813;
        padding: 3px 15px;
        background-color: #fff;
        border-radius: 0 0 0 10px;
      }
      &.jjdq {
        border: 1px solid #eb8200;
        .top {
          background-color: #fab562;
        }
        .sign {
          color: #eb8200;
        }
      }
      &.dq {
        border: 1px solid #da6565;
        .top {
          background-color: #da6565;
        }
        .sign {
          color: #da6565;
        }
      }
      &.wkt {
        border: 1px solid #b5b5b5;
        .top {
          background-color: #b5b5b5;
        }
        .sign {
          color: #b5b5b5;
        }
      }
    }
  }
}

.list-box {
  flex-wrap: wrap;
}
.plantform-item {
  // width: 110px;
  cursor: pointer;
  line-height: 28px;
  overflow: hidden;
  text-align: center;
  border: 1px solid $grey;
  border-radius: 3px;
  padding: 0 20px;
  margin-right: 20px;
  margin-bottom: 10px;
  white-space: nowrap;
}

.allQudao {
  margin-bottom: 15px;
}
</style>
